// 配置路由的地方
import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter)

import routes from './routes'

// 导航守卫 处理登录后不能在跳转login问题
import store from '@/store/index.js'

let originPush = VueRouter.prototype.push
let orignReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject)
  } else {
    originPush.call(this, location, () => {}, () => {})
  }
}

VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    orignReplace.call(this, location, resolve, reject)
  } else {
    orignReplace.call(this, location, () => {}, () => {})
  }
}

let router = new VueRouter({
  routes,
  // 滚动行为 跳转详情页后在顶部
  scrollBehavior () {
    return {y : 0}
  }
})

// 全局前置守卫
router.beforeEach (async(to, from, next) => {
  // next:放行函数： next (), next (path),        next (false)
  // 用户登录，有token
  let token = store.state.user.token
  let name = store.state.user.userInfo.name
  if (token) {
    if (to.path == '/login') {
      next ('/home')
    } else {
      // 登陆了 去的不是login
      if (name) {
        next ()
      } else {
        // 没有用户信息， 派发action让仓库存储用户信息跳转
        try {
          await store.dispatch ('getUserInfo')
          next ()
        } catch (error) {
          // token失效了 获取不到用户信息 
          // 1.清除token 2.从新登录
          await store.dispatch ('userLogout')
          next ('/login')
        }
      }
    }
  } else {
    // 未登录：不能去交易相关、支付相关、个人中心
    // 如果去这些页，得去登录页，不是的话就放行
    let toPath = to.path
    if (toPath.indexOf ('/trade') != -1 || toPath.indexOf ('/pay') != -1 || toPath.indexOf ('/center') != -1) {
      // 未登录点击我的订单--让你登录页---登录页之后应该跳转到我的订单 而不是home页：query参数解决
      next (`/login?redirect=${toPath}`)
    } else {
      // 去home search shopcart放行
      next ()
    }
  }
})

export default router
